/***********************************************
 This file is part of redia-lib-utils-ios.
 
 Copyright (c) 2014 Redia A/S
 
 Redia-library-app-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-library-app-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-library-app-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

#import "RediaPhpFileUploader.h"

@interface RediaPhpFileUploader ()

@property (strong, nonatomic) NSURLConnection *connection;
@property (strong, nonatomic) NSMutableData *responseData;
@property (strong, nonatomic) RediaMutableURLRequest* request;

@property (nonatomic) BOOL didFail;

@end

@implementation RediaPhpFileUploader

- (void)uploadData:(NSData *)data
{
    [self uploadData:data contentType:@"application/octet-stream"];
}

- (void)uploadImageAsJPEG:(UIImage *)image
{
    [self uploadData:UIImageJPEGRepresentation(image, 0.9) contentType:@"image/jpeg"];
}

- (void)uploadImageAsPNG:(UIImage *)image
{
    [self uploadData:UIImagePNGRepresentation(image) contentType:@"image/png"];
}

- (void)uploadData:(NSData *)data contentType:(NSString *)contentType
{
    [self uploadData:data contentType:contentType name:@"uploaded-file" filename:[[NSUUID UUID] UUIDString]];
}

- (void)uploadData:(NSData *)data contentType:(NSString *)contentType name:(NSString*)name filename:(NSString*)filename
{
    self.request = [RediaMutableURLRequest new];
    self.request.URL = self.uploadUrl;
    [self.request multipartAddData:data contentType:contentType name:name filename:filename];
    [self.request multipartFinish];
    self.connection = [NSURLConnection connectionWithRequest:self.request delegate:self];
    [self.connection start];
}

-(void)uploadWithUrlRequest:(RediaMutableURLRequest *)request
{
    self.request=request;
    self.request.URL = self.uploadUrl;
    [self.request multipartFinish];
    self.connection = [NSURLConnection connectionWithRequest:self.request delegate:self];
    [self.connection start];
}

- (void)cancel
{
    [self.connection cancel];
    self.connection = nil;
}

#pragma mark - NSURLConnectionDelegate

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    if (self.delegate) {
        [self.delegate uploadFailed:self.request error:[NSString stringWithFormat:@"Connection error: %@", [error localizedDescription]]];
    }
    self.connection = nil;
    self.request = nil;
}


#pragma mark - NSURLConnectionDataDelegate

- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
    if (self.delegate) {
        [self.delegate uploadProgress:totalBytesWritten expectedTotal:totalBytesExpectedToWrite];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSInteger statusCode = [(NSHTTPURLResponse*)response statusCode];
    if (statusCode == 200) {
        self.responseData = [NSMutableData new];
    }
    else {
        self.didFail=YES;
        if (self.delegate) {
            [self.delegate uploadFailed:self.request error:[NSString stringWithFormat:@"HTTP error. Status code %d", statusCode]];
        }
        self.responseData = nil;
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    if (!self.didFail) {
        if (self.delegate) {
            [self.delegate uploadSucceededFromRequest:self.request responseData:[NSData dataWithData:self.responseData]];
        }
    }
    self.connection = nil;
    self.request = nil;
}

@end
